﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;

namespace LINQFun
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private static readonly string DATAPATH = @"http://www.fizyka.umk.pl/wfaiis/?q=node/17&s=1";
        private BackgroundWorker bWorker;
        public event PropertyChangedEventHandler PropertyChanged;

        private int resREcords;
        public int ResREcords
        {
            get { return resREcords; }
            set
            {
                resREcords = value;
                OnPropertyChanged("ResREcords");
            }
        }

        private List<DataRow> fData;
        public List<DataRow> FData
        {
            get { return fData; }
            set { fData = value; }
        }

         

        private List<DataRow> extData;
        public List<DataRow> ExtData
        {
            get { return extData; }
            set
            {
                extData = value;
                OnPropertyChanged("ExtData");
                ResREcords = ExtData.Count;
            }
        }

        private string rawData;
        public string RawData
        {
            get { return rawData; }
            set
            {
                rawData = value;
                OnPropertyChanged("RawData");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
        {



        }

        private void ExtrudeData()
        {
            Regex calosc = new Regex(@"otOkna\(('(([^']*)'(,|\)){0,1}(\s){0,1}))+");
            var mc = calosc.Matches(rawData);
            foreach (Match m in mc)
            {
                CaptureCollection c = m.Groups[3].Captures;
                int index = c[7].Value.IndexOf(',');
                string stanowisko = c[7].Value;

                if (index > 0)
                    stanowisko = stanowisko.Remove(index);

                DataRow newRow = new DataRow
                {
                    Imie = c[0].Value,
                    Nazwisko = c[1].Value,
                    Telefon = c[2].Value,
                    Pokoj = c[3].Value,
                    Stopien = c[4].Value,
                    Strona = c[5].Value,
                    Zaklad = c[6].Value,
                    Stanowisko = stanowisko,
                    Funkcja = c[8].Value,
                    Jednostka = c[9].Value,
                    Foto = c[10].Value,
                    Mail = c[11].Value,
                };

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { ExtData.Add(newRow); }));
            }
        }

        private void DownloadData()
        {
            using(WebClient webCl = new WebClient())
            {
                webCl.Encoding = Encoding.UTF8;
                RawData = webCl.DownloadString(DATAPATH);    
            } 
                          
        }

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if( handler != null )
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            if(String.IsNullOrEmpty(rawData))
            {
                try
                {
                    ExtData = new List<DataRow>();

                    bWorker = new BackgroundWorker();
                    bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
                    bWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);
                    bWorker.RunWorkerAsync();


                } catch(WebException ex)
                {
                    MessageBox.Show("Brak podłączenia do Internetu.");
                }
            } else 
                FilterData();
        }

        void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            PBar.Visibility = Visibility.Collapsed;
            SearchButton.Content = "search";
            SearchButton.IsEnabled = true;
        }

        void bWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
            {
                SearchButton.IsEnabled = false;
                PBar.Visibility = Visibility.Visible;
            }));

            DownloadData();
            ExtrudeData();

            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                                                                             {
                                                                                 ResREcords = ExtData.Count;
                                                                                 FData = new List<DataRow>(ExtData);
                                                                                 Height = 700;
                                                                                 Width = 750;
                                                                                 Data.Visibility = Visibility.Visible;
                                                                             }));
        }

        private void FilterData()
        {

                List<DataRow> dRow = new List<DataRow>();
                string lowered = SearchBox.Text.ToLower();

                dRow = (from c in FData
                        where
                            c.Imie.ToLower().Contains(lowered) ||
                            c.Nazwisko.ToLower().Contains(lowered) ||
                            c.Telefon.Contains(lowered) ||
                            c.Pokoj.Contains(lowered) ||
                            c.Stopien.ToLower().Contains(lowered) ||
                            c.Strona.ToLower().Contains(lowered) ||
                            c.Zaklad.ToLower().Contains(lowered) ||
                            c.Stanowisko.ToLower().Contains(lowered) ||
                            c.Funkcja.ToLower().Contains(lowered) ||
                            c.Jednostka.ToLower().Contains(lowered) ||
                            c.Mail.ToLower().Contains(lowered)
                        select c).ToList();

                ExtData = dRow;   
        }

        private void SearchBox_KeyUp(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter && FData.Count > 0)
                FilterData();

        }

        private void prof_Checked(object sender, RoutedEventArgs e)
        {
            ExtData = (from c in FData where c.Stopien.Contains("prof") select c).ToList();
        }

        private void dr_Checked(object sender, RoutedEventArgs e)
        {
            ExtData = (from c in FData where c.Stopien.Contains("dr") && !c.Stopien.Contains("hab.") select c).ToList();
        }

        private void hab_Checked(object sender, RoutedEventArgs e)
        {
            ExtData = (from c in FData where c.Stopien.Contains("hab.") && !c.Stopien.Contains("prof") select c).ToList();
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            ExtData =
                (from c in FData where c.Pokoj.Split(',').Length > 1 select new DataRow(){ Imie = c.Imie, Nazwisko = c.Nazwisko, Pokoj = c.Pokoj}  ).ToList();
        }

        private void none_Checked(object sender, RoutedEventArgs e)
        {
            ExtData = FData;
        }

        private void maxNaz_Checked(object sender, RoutedEventArgs e)
        {
            ExtData = (from c in FData where c.Nazwisko.Split(',')[0].Length == FData.Max(m => m.Nazwisko.Split(',')[0].Length) select c).ToList();

        }

    }
}
